<template>
  <div class="permission-container">
    <div class="app-container">
      <el-card>
        <div style="text-align: right; margin-bottom: 20px">
          <el-button type="primary" size="small" @click="showDialog(1,'0')">添加权限</el-button>
        </div>
        <!-- 表格 -->
        <el-table border :data="list" row-key="id">
          <el-table-column label="名称" prop="name" />
          <el-table-column label="标识" prop="code" />
          <el-table-column label="描述" prop="description" />
          <el-table-column label="操作">
            <template #default="{ row }">
              <el-button type="text" @click="showDialog(2,row.id)">添加</el-button>
              <el-button type="text" @click="edit(row)">编辑</el-button>
              <el-button type="text" @click="delFn(row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 弹窗 -->
        <permission-dialog ref="PermissionDialogRef" :visible="visible" :type="type" :pid="pid" @close="close" @update="fetchPermissionList" />
      </el-card>
    </div>
  </div>
</template>

<script>
import PermissionDialog from './components/permission-dialog.vue'
import { getPermissionList, delPermission } from '@/api'
import findSon from '@/utils/findSon'
import { Message } from 'element-ui'
export default {
  name: 'Permission',
  components: {
    PermissionDialog
  },
  data() {
    return {
      list: [],
      visible: false,
      type: '',
      pid: ''
    }
  },
  created() {
    this.fetchPermissionList()
  },
  methods: {
    // 封装表格数据接口
    // 转换树形数据
    async fetchPermissionList() {
      const { data } = await getPermissionList()
      this.list = findSon(data, '0')
    },
    // 打开弹窗
    // 记录当前添加的关键信息
    showDialog(type, pid) {
      this.visible = true
      this.type = type
      this.pid = pid
    },
    // 弹窗关闭
    close() {
      this.visible = false
    },

    // 点击编辑按钮获取子组件中的详情
    // 打开子组件弹窗
    // 可以采用父组件中调用子组件方法的方式实现详情的获取
    // 因为dom的更新是异步的
    // 父传子是同步的
    // 当弹窗打开的时候会获取不到传入的数据
    edit(row) {
      this.visible = true
      this.$refs.PermissionDialogRef.getDetail(row.id)
    },

    // 删除权限点
    // 二次询问，确认删除
    // 提示用户
    // 刷新列表
    async delFn(row) {
      this.$confirm('此操作将永久删除该权限点, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        await delPermission(row.id)
        Message.success('删除权限点成功')
        this.fetchPermissionList()
      }).catch(() => {
        Message('取消')
      })
    }
  }
}
</script>

<style>

</style>
